/*
 * @lc app=leetcode.cn id=25 lang=javascript
 *
 * [25] K 个一组翻转链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
var reverseKGroup = function (head, k) {
  // 开始节点a,结束节点b K 个一组翻转链表
  let reverseLink = (linkA, linkB) => {
    let cur = linkA
    let pre = null
    while (cur != linkB) {
      let next = cur.next
      cur.next = pre
      pre = cur
      cur = next
    }
    return pre
  }
  let linkA = head
  let linkB = head
  for (let i = 0; i < k; i++) {
    if (!linkB) return head
    linkB = linkB.next
  }
  let newList = reverseLink(linkA, linkB)
  head.next = reverseKGroup(linkB, k)
  return newList
}
// @lc code=end
